package com.xjzd.std.thread;

/**
 * 不推荐使用volatile标记位终止线程
 */
public class StopThread {

    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Running...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // 重新设置中断状态
                    System.out.println("Interrupted!");
                    break;
                }
            }
        };

        Thread thread = new Thread(task);
        thread.start();
        Thread.sleep(3000); // 主线程休眠5秒后中断子线程
        thread.interrupt();
    }
}
